import { useModelStore } from '@app-nextmesh/store/model';
import { useProjectStore } from '@app-nextmesh/store/project';
import { ModelEventType, ModelTheme } from '@app-nextmesh/types';
import { events } from '@app-nextmesh/utils';
import { useEffect, useState } from 'react';
import NativeSelect from './NativeSelect';
import { ISelectProps } from './types';

export default function ElementSetSelect(props: ISelectProps) {
  const collections = useProjectStore(
    (state) => state.projectInfo?.collections,
  );
  const [value, setValue] = useState<string[]>([]);
  const [options, setOptions] = useState<any[]>([]);
  // 模型是否加载完成
  const modelLoaded = useModelStore((state) => state.loaded);
  const modelTheme = ModelTheme.Source;
  useEffect(() => {
    setValue([]);
    const values = props.value as string[];
    setValue(values);
    if (!modelLoaded) {
      return;
    }
    if (Array.isArray(collections)) {
      setOptions(
        collections
          ?.filter((item) => item.Type === props.type)
          ?.map((item) => {
            return { label: item.Name, value: item.Name };
          }),
      );
    }
    selectIndices(values);
  }, [props.value, modelLoaded, collections]);

  const selectIndices = (values: string[]) => {
    const indices: string[] = [];
    collections?.forEach((item) => {
      if (values) {
        if (values.includes(item?.Name) && item?.SelectedEntities?.length > 0) {
          indices.push(...item.SelectedEntities);
        }
      }
    });
    // 获取选中的elementSets
    events.emit(ModelEventType.SetPicked, {
      indices,
      theme: modelTheme,
    });
  };
  const handleInputChange = (value: string | number | string[]) => {
    const values = value as string[];
    props.onChange(values);
    setValue(values);
    selectIndices(values);
  };

  return (
    <NativeSelect
      value={value}
      onChange={(value) => handleInputChange(value)}
      options={options}
      disabled={props.disabled}
      multiple={true}
    />
  );
}
